package com.group02.community.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.group02.community.entity.user.SysUser;
import com.group02.community.entity.user.SysUserPost;
import com.group02.community.entity.user.SysUserRole;
import com.group02.community.entity.vo.queryVO.QueryParamsVO;
import com.group02.community.listen.DataListener;
import com.group02.community.mapper.UserMapper;
import com.group02.community.service.IUserPostService;
import com.group02.community.service.IUserRoleService;
import com.group02.community.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, SysUser> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IUserPostService userPostService;

    @Autowired
    private IUserRoleService userRoleService;

    @Autowired
    private BCryptPasswordEncoder bc;


//    @Override
//    public List<SysMenu> getMenusByUsername(String name) {
//        return null;
//    }
//
//    /**
//     * 根据用户名查询用户信息
//     * @return
//     */
//    @Override
//    public  SysUser  getSysUserByUsername(String userName) {
//        return userMapper.getSysUserByUsername(userName);
//    }

    @Override
    public IPage<SysUser> getUserPage(Long current, Long size, QueryParamsVO qp) {
        return userMapper.selectUserPage(new Page<SysUser>(current,size),qp);
    }

    @Override
    public void exportExcel(HttpServletResponse resp) throws IOException {
        //查询所有数据
        List<SysUser> allOwner = userMapper.selectList(null);
        //设置文件下载
        //设置响应头，告诉浏览器要以文件的形式保存
        resp.setHeader("content-disposition","attachment;filename="+System.currentTimeMillis()+".xlsx");
        //生成Excel并写入
        EasyExcel.write(resp.getOutputStream(),SysUser.class).sheet(System.currentTimeMillis()+"").doWrite(allOwner);
    }

    @Override
    @Transactional
    public String saveAllUserMsg(SysUser user) {
        SysUser findUser = userMapper.selectOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getUserName, user.getUserName()));
        if (findUser==null){
            //设置用户密码
            user.setPassword(bc.encode(user.getPassword()));
            userMapper.insert(user);
            SysUser newUser = userMapper.selectOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getUserName, user.getUserName()));
            //获取user的id
            long userId = newUser.getUserId();

            //批量增加用户岗位
            List<Long> postIds = user.getPostIds();
            ArrayList<SysUserPost> userPosts = new ArrayList<>();
            SysUserPost sysUserPost = new SysUserPost();
            for (int i = 0; i < postIds.size(); i++) {
                sysUserPost.setUserId(userId);
                sysUserPost.setPostId(postIds.get(i));
                userPosts.add(sysUserPost);
            }
            userPostService.saveBatch(userPosts);

            //批量增加用户角色
            List<Long> roleIds = user.getRoleIds();
            ArrayList<SysUserRole> userRoles = new ArrayList<>();
            SysUserRole sysUserRole = new SysUserRole();
            for (int i = 0; i <roleIds.size(); i++) {
                sysUserRole.setUserId(userId);
                sysUserRole.setRoleId(roleIds.get(i));
                userRoles.add(sysUserRole);
            }
            userRoleService.saveBatch(userRoles);
            return "添加成功";
        }
        return "用户名重复";

    }

    @Override
    public void importExcel(MultipartFile file) {
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        EasyExcel.read(inputStream, SysUser.class, new DataListener(this)).sheet().doRead();
    }

    @Override
    public void emptyDatabase() {
        userMapper.emptyDatabase();
    }

    @Override
    public void removeByAllIds(String ids) {
        userMapper.removeByAllIds(ids);
    }

    @Override
    @Transactional
    public String updateAllUserMsg(SysUser user) {

        long userId = user.getUserId();

        //批量增加用户岗位
        List<Long> postIds = user.getPostIds();
        ArrayList<SysUserPost> userPosts = new ArrayList<>();
        SysUserPost sysUserPost = new SysUserPost();
        for (int i = 0; i < postIds.size(); i++) {
            sysUserPost.setUserId(userId);
            sysUserPost.setPostId(postIds.get(i));
            userPosts.add(sysUserPost);
        }
        userPostService.saveOrUpdateBatch(userPosts);

        //批量增加用户角色
        List<Long> roleIds = user.getRoleIds();
        ArrayList<SysUserRole> userRoles = new ArrayList<>();
        SysUserRole sysUserRole = new SysUserRole();
        for (int i = 0; i <roleIds.size(); i++) {
            sysUserRole.setUserId(userId);
            sysUserRole.setRoleId(roleIds.get(i));
            userRoles.add(sysUserRole);
        }
        userRoleService.saveOrUpdateBatch(userRoles);

        userMapper.updateById(user);
        return null;
    }

    @Override
    @Transactional
    public Map<String, Long> getUserRoleAndPost(Long id) {
        Map<String, Long> map = new HashMap<>();
        SysUserPost post = userPostService.getOne(new QueryWrapper<SysUserPost>().lambda().eq(SysUserPost::getUserId, id));
        SysUserRole role = userRoleService.getOne(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId, id));
        if (post==null){
            map.put("roleIds",-1L);
        }else {
            map.put("roleIds",role.getRoleId());
        }
        if (role==null){
            map.put("postIds",-1L);
        }else {
            map.put("postIds",post.getPostId());
        }
        return map;
    }


}
